﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using prohomework.Models;
using System.Data.SqlClient;
using System.IO;
using System.IO.Compression;
using System.Text;
using Ionic.Zip;
using System.Reflection;

namespace prohomework.Controllers
{
 //  [ Authorize]
    public class TeacherController : Controller
    {
        //
        // GET: /Teacher/

        #region teacher


        //[AttributeUsage(AttributeTargets.Method)]
        //public class MultipleButtonAttribute : ActionNameSelectorAttribute

        //{
        //    public string Name{get; set;}
        //    public string Argument { get; set; } 


        //  public override bool IsValidName(ControllerContext  controllerContext ,string actionName,MethodInfo methodInfo )
        //  {
        //      var isvalidName=false;
        //      var keyValue=string.Format("{0},{1}",Name,Argument);
        //      var value=controllerContext.Controller.ValueProvider.GetValue(keyValue);
        //      if(value!=null)
        //      {
        //          controllerContext.Controller.ControllerContext.RouteData.Values[Name]=Argument;
        //          isvalidName=true;


        //      }
        //      return isvalidName;

        //  }

        //}

        //多action提交
        public class MultiButtonAttribute : ActionNameSelectorAttribute
        {
            public string Name { get; set; }
            public MultiButtonAttribute(string name)
            {
                this.Name = name;
            }
            public override bool IsValidName(ControllerContext controllerContext,
                string actionName, MethodInfo methodInfo)
            {
                if (string.IsNullOrEmpty(this.Name))
                {
                    return false;
                }
                return controllerContext.HttpContext.Request.Form.AllKeys.Contains(this.Name);
            }
        }  


        public List<SelectListItem> GetdropdowList(string sql,string value,string text)
        {

            //     string sql = "Select * from teacher where username='"+Session["username"] + "'";
            List<SelectListItem> courselist = new List<SelectListItem>();
            TeacherControllerBL courselists = new TeacherControllerBL();
            courselist = courselists.GetAll(sql, value, text);
            //sqlconnection conn = new dbconnection().conn;
            //sqlcommand com = conn.createcommand();
            //com.commandtext = sql;
            //conn.open();
            //sqldatareader reader = com.executereader();




            //while (reader.read())
            //{
            //    selectlistitem s = new selectlistitem();
            //    s.value = reader[value].tostring();
            //    s.text = reader[text].tostring();

            //    courselist.add(s);
            //}
            //reader.close();
            //conn.close();
            return courselist;
        }
        //Request.UserHostAddress.ToString();
        public IEnumerable<homeworkIndex> GethomeworkList(string sql)
        {

            //     string sql = "Select * from teacher where username='"+Session["username"] + "'";
            List<homeworkIndex> courselist = new List<homeworkIndex>();
         //   List<homeworkIndex> ss = new List<homeworkIndex>();
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
          //  SqlHelper rr = new SqlHelper();
           // rr.ExecuteReader()
            int  i=1;
            while (reader.Read())
            {
                //if (reader["filename"].ToString() !="")
                //{
                string dropdownlistsql = "Select * from CheckList";
                List<SelectListItem> drowdownlistdata = GetdropdowList(dropdownlistsql, "id", "批阅名称");


                    homeworkIndex s = new homeworkIndex();
                    s.piyue = SetDropDownListSelectOption(reader["评定"].ToString(), drowdownlistdata);
                    s.datetime = reader["提交时间"].ToString();
                    s.xuhao = i.ToString();
                    s.xuehao = reader["学号"].ToString();
                    s.name = reader["姓名"].ToString();
                    s.ipadress = reader["HostIP"].ToString();
                    s.pizhi = reader["批注"].ToString();
                    s.filename = reader["filename"].ToString();
                    i++;
                    courselist.Add(s);
         //       }
            }
            reader.Close();
            conn.Close();
            return courselist as IEnumerable<homeworkIndex>;
        }

        public List<SelectListItem> SetDropDownListSelectOption(string  seleceid, List<SelectListItem> dropdownlistdata) 
        {
            if (seleceid =="") seleceid = "0";
                foreach (var item in dropdownlistdata)
                {
                    if (item.Value == seleceid)
                        item.Selected = true;
                
                
                }
                return dropdownlistdata;
        }


        public ActionResult Download(string xuehao, string workid)
        {
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");


            string sql = "SELECT * from sthomework where 学号='" + xuehao + "' and HomeworkID='" + workid + "'";
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            byte[] filedata = null;
            string fileContentType = null;
            string filename = null;
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                filedata = (byte[])reader["filecontent"];
                fileContentType = reader["fileContentType"].ToString();
                filename = reader["filename"].ToString();
            }
            if(fileContentType=="")
            {
             string fileExtension = Path.GetExtension(filename);
                if(fileExtension==".doc"||fileExtension==".docx")  fileContentType="application/msword";
            else{
                fileContentType = "application/octet-stream";
                
                }
            
            }
            reader.Close();
            conn.Close();
            //   var fattach = new FileContentResult(filedata, "application/octet-stream");  
            //  var ss=new file
            return File(filedata, fileContentType, filename);
        }  
            //using (var memoryStream = new MemoryStream())
            //{
            //    using (var ziparchive = new  ZipArchive(memoryStream, ZipArchiveMode.Create, true))
            //    {
            //        for (int i = 0; i < 10; i++)
            //        {
            //            var readmeEntry = ziparchive.CreateEntry(string.Format("File_{0}.txt", i));
            //            using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
            //            {
            //                writer.WriteLine(string.Format("File_{0} - Contents", i));
            //            }
            //        }
            //        ziparchive.
            //        ziparchive.CreateEntryFromFile(Server.MapPath("~/Files/file2.txt"), "file2.txt");
            //        ziparchive.CreateEntryFromFile(Server.MapPath("~/Files/file3.txt"), "file3.txt");
            //    }

            //    return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
            //}

 //using (ZipFile zip = new ZipFile(System.Text.Encoding.Default))
 //   {
 //       zip.AlternateEncodingUsage = ZipOption.AsNecessary;
 //       zip.AddDirectoryByName("Files");
 //       foreach (GridViewRow row in GridView1.Rows)
 //       {
 //           if ((row.FindControl("chkSelect") as CheckBox).Checked)
 //           {
 //               string filePath = (row.FindControl("lblFilePath") as Label).Text;
 //               zip.AddFile("d",
 //           }
 //       }


 //         //  return View();
 //       }

     //   public 

        public ActionResult TeacherIndex()
        {
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");


            string sqlcurse = "Select distinct CourseID, 课程名称 as CourseName from studentclasscourse Where TeacherID='" + Session["username"] + "'";

            ViewData["courselist"] = GetdropdowList(sqlcurse, "CourseID", "CourseName");
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "1", Value = "1", Selected = true });
            items.Add(new SelectListItem { Text = "2", Value = "2" });
            items.Add(new SelectListItem { Text = "3", Value = "3" });
            items.Add(new SelectListItem { Text = "4", Value = "4" });
            items.Add(new SelectListItem { Text = "5", Value = "5" });
            items.Add(new SelectListItem { Text = "6", Value = "6" });
            items.Add(new SelectListItem { Text = "7", Value = "7" });
            items.Add(new SelectListItem { Text = "8", Value = "8" });
            items.Add(new SelectListItem { Text = "9", Value = "9" });
            items.Add(new SelectListItem { Text = "10", Value = "10" });
            ViewData["list"] = items;
            return View();
        }

        //  [HttpPost]
        public ActionResult HomeworIndex(string zuoyelist, string classeslist) 
        {
           // string a = form["zuoyelist"];
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");


          string 	str = "select student.学号, 姓名, 专业名称, isnull(帐号,'') as 帐号, 提交时间, 作业文件, isnull([filename],'<无>') as filename, HostIP, 评定, 批注  from sthomework inner join student on student.学号=sthomework.学号 ";
          str = str + " where HomeworkID=" + zuoyelist + " and student.班级代码='" + classeslist + "' union ";
	        str = str + " select 学号, 姓名, 专业名称, isnull(帐号,'') as 帐号, null as 提交时间, null as 作业文件, '' as filename, null as HostIP, null as 评定, null as 批注 from student ";
            str = str + " where 班级代码='" + classeslist + "' and 学号 not in (select student.学号  from sthomework inner join student on ";
            str = str + " student.学号=sthomework.学号 where HomeworkID=" + zuoyelist + " and student.班级代码='" + classeslist + "')";        
         string sqlhomeworkname=   "Select * from homework where id=" + zuoyelist + "";
         ViewData["zuoyename"] = GetName(sqlhomeworkname, "作业名称");
           string sqlclassname=  " Select * from Class where 班级代码='"+ classeslist + "'";
           ViewData["classname"] = GetName(sqlclassname, "专业名称");

          IEnumerable<homeworkIndex > datamodel= GethomeworkList(str);
         ViewData["listcount"]= datamodel.Count();
         ViewData["zuoyeid"] = zuoyelist;
          return View(datamodel);
        }

              [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult ActiveAreas(string courselist)
        {
          //  int courseid = Convert.ToInt32(courselist);
            string Sqlclass = "Select distinct 班级代码 as ClassID, ClassName from studentclasscourse Where TeacherID='" + Session["username"] + "'" + "and CourseID='" + courselist + "'" + "Order By ClassName";
            string Sqlzuoye = "Select ID,作业名称 from Homework Where 课程号='" + courselist + "'";

          //  var areas = from n in Db.question where n.questionsetid == questionsetid select n; //LINQ代码从数据库读数据
          //  var areaList = areas.ToList();
          //  var areaData = areaList.Select(a => new SelectListItem() { Value = a.questionmumber.ToString(), Text = a.questionmumber.ToString() });
            var areaData = GetdropdowList(Sqlclass, "ClassID", "ClassName");
           // var zuoyedata = GetdropdowList(Sqlclass, "ID", "作业名称");
            return Json(areaData, JsonRequestBehavior.AllowGet);
          //  return JsonResult();
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult ActiveAreaszuoye(string courselist)
        {
            //  int courseid = Convert.ToInt32(courselist);
          //  string Sqlclass = "Select distinct 班级代码 as ClassID, ClassName from studentclasscourse Where TeacherID='" + Session["username"] + "'" + "and CourseID='" + courselist + "'" + "Order By ClassName";
            string Sqlzuoye = "Select id,作业名称 from Homework Where 课程号='" + courselist + "'";

            //  var areas = from n in Db.question where n.questionsetid == questionsetid select n; //LINQ代码从数据库读数据
            //  var areaList = areas.ToList();
            //  var areaData = areaList.Select(a => new SelectListItem() { Value = a.questionmumber.ToString(), Text = a.questionmumber.ToString() });
            //var areaData = GetdropdowList(Sqlclass, "ClassID", "ClassName");
            var zuoyeData = GetdropdowList(Sqlzuoye, "id", "作业名称");
            return Json(zuoyeData, JsonRequestBehavior.AllowGet);
            //  return JsonResult();
        }

    //    public ActionResult 
        //public static void UpdateHomework() //修改
        //{

        //    SqlConnection conn = new DBConnection().Conn;
        //    SqlCommand com = conn.CreateCommand();
        //    com.CommandText = sql;
        //    conn.Open();
        //    int sss = com.ExecuteNonQuery();

        //    if (intres > 0)
        //    {
        //        Console.WriteLine("修改成功");
        //    }
        //    else
        //    {
        //        Console.WriteLine("修改失败");
        //    }
        //}


        public bool UpdateHomework(string xuehao, int zuoyeid, string piyue, string pizhi)
        {
            bool b = false;
//='" & stno & "' and HomeworkID=" & Session("Workid")
            //string sql = "select COUNT(*) from Users where username=@username and userpass=@userpass";
            string sql = "update sthomework set 评定 = @piyue,批注=@pizhi,批阅时间=@datetime where 学号=@xuehao and HomeworkID=@zuoyeid";

            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();

            com.Parameters.Add(new SqlParameter("@xuehao", xuehao));
            com.Parameters.Add(new SqlParameter("@zuoyeid", zuoyeid));
            com.Parameters.Add(new SqlParameter("@piyue", piyue));
            com.Parameters.Add(new SqlParameter("@pizhi", pizhi));
            com.Parameters.Add(new SqlParameter("@datetime", DateTime.Now));
            com.CommandText = sql;

            conn.Open();
            try
            {
                int  obj = com.ExecuteNonQuery();
              //  int count = Convert.ToInt32(obj);
                if (obj > 0)
                    b = true;
            }
            finally
            {
                conn.Close();
            }
            return b;
        }





        [HttpPost]
        [MultiButton("tijiao")]
        [ValidateInput(false)]
        public ActionResult tijiao(FormCollection form) 
        {
            int zuoyeid = Convert.ToInt32(form["zuoyeid"]);
            for (int i = 1; i <= Convert.ToInt32(form["listcount"]); i++)
            {
                string xuehao = form[i.ToString()];
                string namepiyue = "piyue" + i.ToString();
                string namepizhi = "pizhi" + i.ToString();
                string piyue = form[namepiyue];
                string pizhi = form[namepizhi];
                UpdateHomework(xuehao, zuoyeid, piyue, pizhi);
            }

            return View("tijiao");
        }



        [HttpPost]
        [MultiButton("mutipledownload")]
        [ValidateInput(false)]
        public ActionResult mutipledownload( FormCollection form)
        {
            if (Session["username"] == null || Session["username"].ToString() == "") return RedirectToAction("Login", "Account");
            string ids = form["ckSelect"];
            int zuoyeid = Convert.ToInt32(form["zuoyeid"]);
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
           // SqlDataReader reader = null;
            conn.Open();
            ZipFile zip = new ZipFile(System.Text.Encoding.UTF8);
                        foreach (var item in ids.Split(','))//循环每一项Id
                        {
                            if (item != "false")//筛选掉自动生成的checkbox初始值
                            {

                                string sql = "SELECT * from sthomework where 学号='" + item + "' and HomeworkID='" + zuoyeid + "'";
                                com.CommandText = sql;
                                byte[] filedata = null;
                                string fileContentType = null;
                                string filename = null;
                                SqlDataReader reader = com.ExecuteReader();
                                while (reader.Read())
                                {
                                    filedata = (byte[])reader["filecontent"];
                                     if (filedata == null) continue;

                                    fileContentType = reader["fileContentType"].ToString();
                                    filename = reader["filename"].ToString();
                                    if (!filename.Contains(item)) { filename = "(" + item + ")" + filename; }

                                }


                                if (filedata != null)
                                {
                                //filename != "" && fileContentType != "" && filename != null && fileContentType != null
                                  //if (fileContentType != "" && fileContentType != null)
                                    zip.AddEntry(filename, (byte[])filedata.ToArray());
                                }
                                reader.Close();

                            }
                        
                        }

            conn.Close();

            String zipname = form["classname"].ToString() + "_" + form["zuoyename"].ToString() + ".zip";


            var memoryStream = new MemoryStream();
             byte[] zipContentall = null;
            //  zip.AddDirectory(Server.MapPath("~/Images"));
            zip.Save(memoryStream);
              zipContentall = memoryStream.ToArray();
                return File(zipContentall, "application/zip", zipname);



            //var zipMs = new MemoryStream();
            //      zip.Save(zipMs);
            //      byte[] fileData = zipMs.GetBuffer();
            //      zipMs.Seek(0, SeekOrigin.Begin);
            //      zipMs.Flush();
            //      String zipname = form["classname"].ToString() +"_"+ form["zuoyename"].ToString()+".zip";
            //             zipname = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(zipname));
            //       Response.Clear();

            //Response.AddHeader("content-disposition", "attachment;filename=" +zipname);
            //     Response.AddHeader("Content-Length", fileData.Length.ToString());
            //  Response.ContentType = "application/zip";
            //Response.HeaderEncoding = System.Text.Encoding.UTF8;
            //Response.BinaryWrite(fileData);
            //       Response.End();
            //return new EmptyResult();
            //   var fattach = new FileContentResult(filedata, "application/octet-stream");  
            //  var ss=new file
            //   return File(filedata, fileContentType, filename);

            /*    string zipname = form["classname"].ToString() + "_" + form["zuoyename"].ToString() + ".zip";
                var cd = new System.Net.Mime.ContentDisposition
                   {
                       FileName = zipname,
                       Inline = false,
                   };
                   Response.AppendHeader("Content-Disposition", cd.ToString());
                   var memStream = new MemoryStream();
                   zip.Save(memStream);
                   memStream.Position = 0; // Else it will try to read starting at the end
                   return File(memStream, "application/zip");*/
            //  return File(zip., "application/zip", zipname);




        }  


        #endregion

        #region method

            public string GetName(string sql,string name)
             {
            string teachername = "";
            //    string sql = "Select * from teacher where username='"+Session["username"] + "'";
            SqlConnection conn = new DBConnection().Conn;
            SqlCommand com = conn.CreateCommand();
            com.CommandText = sql;
            conn.Open();
            SqlDataReader reader = com.ExecuteReader();
            if (reader.Read())
            {
                teachername = reader[name].ToString();

            }
            reader.Close();
            conn.Close();
            return teachername;
                }
        #endregion






        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Teacher/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Teacher/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Teacher/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Teacher/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Teacher/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Teacher/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Teacher/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
